package com.itheima.service.impl;

import com.itheima.bean.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class UserServiceImpl implements UserService {

    /**
     * 定义登录的方法
     * @return 返回查到的用户信息
     */
    @Override
    public User login(String username,String password) {
        SqlSession sqlSession = null;
        User user = null;
        try {
            //1 加载mybatis核心配置文件
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2 创建SqlSessionFactory对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //3 获取SqlSession对象
            sqlSession = factory.openSession();
            //4 获取UserMapper代理对象
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //5 执行操作，获取结果
            user = userMapper.login(username, password);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //6 返回结果，释放资源
            sqlSession.close();
        }
        return user;
    }
}
